package com.zhongfl.crm.lixiao.batch.service.lx2crm;

import com.heptagram.lixiao.api.LiXiaoService;
import com.heptagram.lixiao.bean.request.LXUserRequest;
import com.heptagram.lixiao.bean.response.LXUserResponse;
import com.heptagram.lixiao.common.exception.LiXiaoErrorException;
import com.zhongfl.crm.enums.UserMatchStatus;
import com.zhongfl.crm.enums.boss.AmibaCode;
import com.zhongfl.crm.lixiao.bean.resolve.UserModelResolver;
import com.zhongfl.crm.model.LxDepartment;
import com.zhongfl.crm.model.LxUser;
import com.zhongfl.crm.model.boss.Amiba;
import com.zhongfl.crm.model.crm.StaffExt;
import com.zhongfl.crm.service.LxDepartmentService;
import com.zhongfl.crm.service.LxUserService;
import com.zhongfl.crm.service.boss.AmibaService;
import com.zhongfl.crm.service.crm.StaffExtService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import tech.heptagram.staff.model.Staff;
import tech.heptagram.staff.service.StaffService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 励销用户同步服务
 *
 * @author wang.yuchuan
 * @date 2018/6/24
 */
@Service
@Slf4j
public class LxUserSyncService {

    @Resource
    private LiXiaoService liXiaoService;

    @Resource
    private LxUserService lxUserService;

    @Resource
    private StaffService staffService;

    @Resource
    private LxDepartmentService lxDepartmentService;

    @Resource
    private AmibaService amibaService;

    @Resource
    private StaffExtService staffExtService;

    public void sync() throws LiXiaoErrorException {
        LXUserRequest request = new LXUserRequest();
        request.setPerPage(100);
        request.setPage(1);

        LXUserResponse lxUserResponse;
        do {
            log.info("查询励销用户信息, 参数: page: {}", request.getPage());
            lxUserResponse = liXiaoService.getUserService().findUsers(request);
            if (lxUserResponse.getData().getTotalCount() == 0) {
                log.info("励销返回用户为空, 不需要同步");
                return;
            }

            List<LXUserResponse.User> lxUsers = lxUserResponse.getData().getUsers();
            if (CollectionUtils.isEmpty(lxUsers)) {
                log.info("励销返回用户为空, 不需要同步");
                return;
            }

            for (LXUserResponse.User lxUser : lxUsers) {

                try {
                    UserModelResolver userModelResolver = new UserModelResolver();
                    LxUser resolveUser = userModelResolver.resolve(lxUser);

                    LxUser user = lxUserService.findByLxId(lxUser.getId());

                    if (Objects.isNull(user)) {
                        //如果匹配到了就新增
                        if (matchUser(lxUser, resolveUser)) {
                            lxUserService.insertUser(resolveUser);
                        }
                    } else {
                        // 如果本地员工已存在, 更新信息
                        resolveUser.setId(user.getId());
                        lxUserService.updateUserById(resolveUser);
                        resolveUser.setStaffCode(user.getStaffCode());
                    }
                    //如果用户的励销部门为报单部门 则新建或更新员工拓展信息
                    LxDepartment lxDepartment = lxDepartmentService.findByLxId(resolveUser.getDepartmentId());
                    if (!ObjectUtils.isEmpty(lxDepartment) && !ObjectUtils.isEmpty(lxDepartment.getAmibaId())) {
                        Amiba amiba = amibaService.findById(lxDepartment.getAmibaId());
                        if (!ObjectUtils.isEmpty(amiba) && AmibaCode.XIAO_SHOU.equals(amiba.getCode())) {
                            StaffExt ext = new StaffExt();
                            ext.setStaffName(resolveUser.getStaffName());
                            if (StringUtils.isEmpty(resolveUser.getStaffName())) {
                                ext.setStaffName(resolveUser.getName());
                            }
                            ext.setStaffCode(resolveUser.getStaffCode());
                            ext.setBusinessDeptId(amiba.getId());
                            ext.setBusinessDeptName(amiba.getName());
                            ext.setCreatedBy("SYSTEM");
                            ext.setModifiedBy("SYSTEM");
                            staffExtService.saveOrUpdateBusinessDept(ext);
                        }
                    }
                } catch (Exception ex) {
                    log.error("保存励销用户数据出错: {}", ex.getMessage(), ex);
                }
            }

            request.setPage(request.getPage() + 1);
        } while (lxUserResponse.getData().hasNextPage());
    }

    private Boolean matchUser(LXUserResponse.User lxUser, LxUser resolveUser) {
        if (Objects.isNull(lxUser) || Objects.isNull(resolveUser)) {
            return false;
        }
        // 本地员工不存在, 根据名称查询员工编码信息
        Staff staff = staffService.getByName(lxUser.getName());

        if (Objects.isNull(staff) && StringUtils.isNotEmpty(lxUser.getPhone())) {
            staff = staffService.getByMobile(lxUser.getPhone());
        }

        if (Objects.nonNull(staff) && Objects.nonNull(staff.getId())) {
            resolveUser.setMatchStatus(UserMatchStatus.YES);
            resolveUser.setLxStatus(UserMatchStatus.YES);
            resolveUser.setStaffCode(staff.getCode());
            resolveUser.setStaffName(staff.getTrueName());
            return true;
        }
        return false;
    }
}
